//This is the notifier file for ObserverPatternV2 12/8/2011

#include "Notifier.h"

Notifier* Notifier::instance = 0;

Notifier::Notifier(void)
{
}


Notifier::~Notifier(void)
{
}

bool Notifier::unsubscribe(Observer* o, event e)
{
	vector<Observer*>::iterator it;

	if (e == KEY_EVENT)
	{
		for ( it=keyEventObservers.begin() ; it < keyEventObservers.end(); it++ )
		{
			if (o == *it)
			{
				keyEventObservers.erase(it);
				cout << "   [Notifier] :Removing a key event subscriber." << endl;
				return true;
			}
		}
	}
	else if (e == CLASS_EVENT)
	{
		for ( it=classEventObservers.begin() ; it < classEventObservers.end(); it++ )
		{
			if (o == *it)
			{
				classEventObservers.erase(it);
				cout << "   [Notifier] Removing a class event subscriber." << endl;
				return true;
			}
		}
	}
	return false;
}


bool Notifier::subscribe(Observer* o, event e)
{
	bool returnValue = false;
	if (e == KEY_EVENT)
	{
		keyEventObservers.push_back(o);
		cout << "   [Notifier] Registered a key event subsciber." << endl;
		returnValue = true;
	}
	else if (e == CLASS_EVENT)
	{
		classEventObservers.push_back(o);
		cout <<"   [Notifier] Registered a class event subscriber." << endl;
		returnValue = true;
	}
	return returnValue;
}


bool Notifier::LogEvent(event e, string data)
{
	switch (e)
	{
	case KEY_EVENT:
		if (!keyEventObservers.empty())
		{
			vector<Observer *>::iterator key_iter;
			for ( key_iter = keyEventObservers.begin(); key_iter != keyEventObservers.end(); key_iter++)
			{
				if (!(*key_iter == NULL))
				{
					(*key_iter)->notify(e, data);
					cout << "   [Notifier] Key Event Sent: data is " << data << endl;
				}
				else
				{
					cout << "   [Notifier] ***WARNING*** NULL pointer found!!!" << endl;
				}
			}
		}
		break;
	case CLASS_EVENT:
		if (!classEventObservers.empty())
		{
			vector<Observer *>::iterator class_iter;
			for ( class_iter = classEventObservers.begin(); class_iter != classEventObservers.end(); class_iter++)
			{
				if (!(*class_iter == NULL))
				{
					(*class_iter)->notify(e, data);
					cout << "   [Notifier] Class Event Sent: data is " << data << endl;
				}
				else
				{
					cout << "   [Notifier] ***WARNING*** NULL pointer found!!!" << endl;
				}
			}
		}
		break;
	default:
		return false;
	}

	return true;
}


Notifier * Notifier::getInstance(void)
{
	if (instance == 0)
	{
		instance = new Notifier();
	}
	return instance;
}
